var handle = new mysql.Database(); 
handle.OPTION_MULTI_STATEMENTS_ON;
var db_name	=	"damogu";
if( handle.connect("localhost", "root", "", db_name) ){ 
	/**
	var tables	=	handle.listTables();
	while(	table = tables.fetchObject()){
		//response.print(	table	);
		for(	var o in table){
			response.print(	o	);
			response.print(	"-------------"	);
			response.print(	table[o]	);
			response.print(	"-------------"	);
		}
		
	}
	**/
}else{

}

/*
 *	取得数据库列表
 *
 */
function getListTablenames(){
	var tables		=	handle.listTables();
	var tablenames	=	Array();
	while(	table = tables.fetchObject()){
		for(	var p in table){
			tablenames.push(	table[p]	)
			//response.print(	o	);
			//response.print(	"-------------"	);
			//response.print(	table[o]	);
			//response.print(	"-------------"	);
		}
	}
	return tablenames;
}
function getRs(sql){
	debug.show(sql);
	var stmt = handle.prepare(	sql	);
	if ( stmt.execute() ){
		return stmt;
	}else{
		return false;
	}
}
/**
 *	插入数据
 */
function insert(	tablename,	sets	){
	//INSERT INTO authors(id, firstname, lastname) VALUES(1, 'JRR', 'Tolkien')
	var code	=	"INSERT INTO "	+	db_name	+	"."	+ tablename;
	var cols	=	" ("
	for(	var col in sets){
		cols	+=	col+",";
	}
	cols	=	cols.substring(0,	cols.length-1	);
	cols	+=	")"
	code	+=	cols;
	var values	=	"VALUES (";
	for(	var col in sets){
		try{
			var type	=	$type(sets[col])
			var value	=	sets[col];
			switch(	type	){
				case "string":
					/**
					 *	允许执行sql
					 */
					if(	value.substring(0,4)	==	'sql:'){
						values	+=	value.substring(	4,	value.length	)+",";
					}else{
						values	+=	"'"+value.escapeRegExpSql()+"',";
					}
					break;
				case "number":
					values	+=	value+",";
					break;
				case "boolean":
					if(	value	){
						values	+=	"1,";
					}else{
						values	+=	"0,";
					}
					break;
			}
		}catch(e){
			response.print(e);
		}
	}
	values	=	values.substring(0,	values.length-1	);
	values	+=	")";
	code	+=	values;
	debug.show(	code	);	
	handle.query(	code	);
	if(handle.error){
		debug.show(	handle.error);	
	}
	var id	=	handle.insertId;
	return id;
}
/*
var handle = new sqlite.Database("books.db");
if ( handle.opened ){ 
	var pragmaStmt = handle.prepare("PRAGMA user_version"); 
	var pragma = pragmaStmt.fetchArray(); 
	if ( pragma[0] == 0 ){
		handle.exec(	"CREATE TABLE authors(id INTEGER PRIMARY KEY, " + 
						"firstname TEXT, lastname INTEGER)");
		handle.exec(	"CREATE TABLE books(id INTEGER PRIMARY KEY, " + 
						"title TEXT, fk_author_id INTEGER)");
		handle.exec(	"PRAGMA user_version = 1");
		handle.exec(	"INSERT INTO authors(id, firstname, lastname) " + 
						"VALUES(1, 'JRR', 'Tolkien')");
		handle.exec(	"INSERT INTO authors(id, firstname, lastname) " +  
						"VALUES(2, 'John', 'Grisham')");
		handle.exec(	"INSERT INTO books(id, title, author) " + 
						"VALUES(1, 'Lords of the ring', 1)");
		handle.exec(	"INSERT INTO books(id, title, author) " + 
						"VALUES(2, 'The firm', 2)");
	} 
}else{
	handle = null;
}
*/